package org.hades.corelib.base.extend

import androidx.lifecycle.*
import com.carman.kotlin.coroutine.exception.GlobalCoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
import kotlin.coroutines.CoroutineContext

/**
 * 扩展了 LifecycleOwner
 * 1、默认GlobalCoroutineExceptionHandler
 * 2、默认生命周期Lifecycle.State.STARTED
 * 3、使用 supervisorScope 特定作用域
 * */
fun LifecycleOwner.doLaunch(
    // 异常处理器
    context: CoroutineContext = GlobalCoroutineExceptionHandler(),
    state: Lifecycle.State = Lifecycle.State.STARTED,
    // block
    block: suspend CoroutineScope.()->Unit
){
    lifecycleScope.launch(context){
        repeatOnLifecycle(state) {
            supervisorScope {
                block.invoke(this)
            }
        }
    }
}

/**
 * 封装了 viewModelScope 使用 supervisorScope 特定作用域
 * */
fun ViewModel.doLaunch(
    // 异常处理
    context: CoroutineContext = GlobalCoroutineExceptionHandler(),
    // block
    block: suspend CoroutineScope.()->Unit
){
    viewModelScope.launch(context){
        supervisorScope {
            block.invoke(this)
        }
    }
}


class ActivityExtention {
}